package com.dahua.messagesyncsh.service.Impl;

import com.alibaba.fastjson2.JSON;
import com.dahua.messagesyncsh.common.Constants;
import com.dahua.messagesyncsh.config.redis.RedisUtil;
import com.dahua.messagesyncsh.criteria.StationQueryCriteria;
import com.dahua.messagesyncsh.entity.Station;
import com.dahua.messagesyncsh.mapper.StationMapper;
import com.dahua.messagesyncsh.service.StationService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

@Service
public class StationServiceImpl implements StationService {
    @Resource
    private RedisUtil redisUtil;

    @Resource
    private StationMapper stationMapper;

    @Override
    public List<Station> enquire(StationQueryCriteria criteria) {

        if(criteria.getId() != null){
            Object hash = redisUtil.getHash(Constants.STATION_INFO, String.valueOf(criteria.getId()));

            /*  缓存返回*/
            if (hash != null){
                if (hash.equals(Constants.NULL)){
                    return Collections.emptyList();
                }
                return Collections.singletonList(JSON.parseObject(JSON.toJSONString(hash), Station.class));
            }

            /*  查询返回*/
            List<Station> enquire = stationMapper.enquire(criteria);

            if (enquire != null && !enquire.isEmpty()){
                redisUtil.setHash(Constants.STATION_INFO, String.valueOf(criteria.getId()), enquire.get(0));
            }else{
                redisUtil.setHash(Constants.STATION_INFO, String.valueOf(criteria.getId()), Constants.NULL);
            }
            return enquire;
        }

        return stationMapper.enquire(criteria);
    }
}
